package video

import (
	"fmt"
	"time"

	"github.com/gogf/gf/v2/container/gvar"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/net/ghttp"
)

type Video struct{}

func New() *Video {
	return &Video{}
}

// post means upload a video
func (v *Video) Post(req *ghttp.Request) {
	files := req.GetUploadFiles("video")

	if files != nil {
		filename, err := files.Save("resource/video")
		if err == nil {
			req.Response.Writeln(filename)
		}
	}
}

// get video metadata
func (v *Video) MetadataGet(req *ghttp.Request) {
  vid := req.GetQuery("videoId")
  if vid != nil {
    filePath := fmt.Sprintf("/resource/public/resource/video_meta/%d.json", vid.Int())
    jsonObj, err := gjson.Load(filePath)
    if err == nil {
      req.Response.WriteJson(jsonObj)
    } else {
      fmt.Println(time.Now(), ": error in load")
    }
  }
}

func (v *Video) NoteGet(req *ghttp.Request) {
	vid := req.GetQuery("videoId")
	noteId := req.GetQuery("noteId")
	if vid != nil {
		filePath := fmt.Sprintf("/resource/public/resource/notes/%d-%d.md", vid.Int(), noteId.Int())
		req.Response.ServeFile(filePath)
	}
}

func (v *Video) VideoGet(req *ghttp.Request) {
	vid := req.GetQuery("videoId")
	resolution := req.GetQuery("resolution")
	if vid != nil {
		if resolution == nil {
			resolution = gvar.New("1080p")
		}
		filePath := fmt.Sprintf("/resource/public/resource/video/%d-%s.mp4", vid.Int(), resolution.String())
		req.Response.ServeFile(filePath)
	}
}

func (v *Video) PosterGet(req *ghttp.Request) {
	vid := req.GetQuery("videoId")
	if vid != nil {
		filePath := fmt.Sprintf("/resource/public/resource/poster/%d.jpg", vid.Int())
		req.Response.ServeFile(filePath)
	}
}

func (v *Video) CaptionGet(req *ghttp.Request) {
	vid := req.GetQuery("videoId")
	if vid != nil {
		filePath := fmt.Sprintf("/resource/public/resource/caption/%d.vtt", vid.Int())
		req.Response.ServeFile(filePath)
	}
}
